//regist.js
//短信模板报备地址https://console.cloud.tencent.com/servicemarket/services/market-nvm314e3e
const app = getApp();
// 初始化云
Page({
  data: {
    phone:'',     //手机号
    codeBtnLabel:'获取验证码',
    phoneBtnLabel:'获取手机号',
    codeBtnDisabled:false,
    saveBtnDisabled:false,
   
    smscode: '',   //系统生成的验证码
    name:'',
    phone_color: 'color:red',
    code_color:'color:red',
    
    codeBtnDisabled:false,
    phoneBtnDisabled:false,
    isCode:null,   //用于存放验证码接口里获取到的Code
    second: 61,
    codeStr:'', 
    address:'',
    school:'',
    mmHidden:true,  //是否隐藏对话框  
    counterId:'' 

  },


getPhoneNumber:function(e){
    console.log(e)
    console.log(e.detail.errMsg)
    console.log(e.detail.iv)
    console.log(e.detail.encryptedData) 
    var that = this
    wx.request({
      url: 'https://www.beicho.com/get_phone.php',          //腾讯官方demo改造的接口页面
      data: {
        iv: e.detail.iv, 
        encryptedData: e.detail.encryptedData,
        session_key:app.globalData.session_key

       },
      method: 'GET', 
      header: {
        'content-type': 'application/json'
      }, 
      success: function (res) {
        // console.log('获取到的手机号:',res.data.phoneNumber)
         that.setData({
           phone:res.data.phoneNumber 
         })
      },
      fail: function (err) {
        console.log(err);
      }
    })

  that.setData({              //将拼接好的字符串赋值给
    phoneBtnDisabled: true,
    phone_color: 'color:gray',
    
  })

  var num = 30;
  var timer = setInterval(function () {
    num--;
    if (num <= 0) {
      clearInterval(timer);
      that.setData({
          phoneBtnLabel: '重新发送',
          phoneBtnDisabled: false,
          phone_color: 'color:red'
      })
    }
    else {
      that.setData({        
        phoneBtnLabel: num + 's'
      })
    }
  }, 1000)

},

 

//手机号输入
  getPhoneValue:function(e) {
    this.setData({
      phone: e.detail.value,

    })

},


//发送验证码
sendVerificationCode:function(){
  //生成验证码
  var _this=this;
  var myreg=/^(14[0-9]|13[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8}$$/;
  if (this.data.phone==""){
    wx.showToast({
       title: '手机号不能为空',
       icon:'none',
       duration:1000
    })
    return false
   } 
   else if (!myreg.test(this.data.phone)){
    wx.showToast({
       title:'请输入正确的手机号',
       icon:'none',
       duration:500
    })
    return false;
  }
  else {
      //**  生成验证码 */
      var codeLength = 6;         //设置长度，设置6位    
      var rdm = new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');   //设置随机字符
      for (var i = 0; i < codeLength; i++) {         //循环codeLength，设置6就是循环6次      
        var index = Math.floor(Math.random() * 9);   //设置随机数范围，这设置为      
        this.data.codeStr += rdm[index];             //字符串拼接，将每次随机的字符进行拼按
      }
   this.setData({
      smscode:this.data.codeStr
   })
    //发送验证码
    var phone=this.data.phone;
    var smscode = this.data.codeStr
   // console.log(this.data.codeStr)   
  
    var plugin = requirePlugin("qcloudsms")
    plugin.sendSMS(
      {
        secretid: 'AKID6Qcmlrja1J0r5J1tlmmaDuYi1UF5kpDQHR1u',
        secretkey: '5tdTuBr8e1Ew9Zkpc9a45ryg9i83ofsh9Yi43su',
        mobile: phone,
        content: '验证码：' + smscode +'，选择卓越，就是选择超越！请您及时完成验证。【卓越易课】'
      },  
      function success(res) {
        if (res.data.message) {
          //console.log(res.data.message)
          wx.showToast({
            title: '验证码已发送',
            icon: 'none',
            duration: 2000,
          });
         
        } else if (res.data.result >= 0) {
          console.log(res.data.errmsg)
        } else {
          console.log(res.data.errmsg)
        }
      },

      function fail(err) {
        console.log(err.errMsg)
        codeBtnDisabled: false,
        wx.showToast({
          title: '验证码发送失败',
          icon: 'none',
          duration: 2000,
        });
      } //fail(err)
    ) //plugin
   
    this.setData({              //将拼接好的字符串赋值给
      codeBtnDisabled: true,
      code_color: 'color:gray',
      mobile:this.data.phone,
      smscode:this.data.smscode   
      
    })


    var num = 30;
    var timer = setInterval(function () {
      num--;
      if (num <= 0) {
        clearInterval(timer);
        _this.setData({
          codeBtnLabel: '重新发送',
          codeBtnDisabled: false,
          code_color: 'color:red'
        })
      }
      else {
        _this.setData({
          codeBtnLabel: num + 's'
         })
          }
     }, 1000)
 
  }  


},



//输入手机短信验证码
getCodeValue: function (e) {
    this.setData({
      isCode: e.detail.value
    })
},


// name
getName: function (e) {
    this.setData({
      name: e.detail.value,

    })
},

//获取用户地址
getAddress: function (e) {
    this.setData({
      address: e.detail.value
    })
},

//获取学校名称
getSchool: function (e) {
    this.setData({
      school: e.detail.value
    })
},



timer: function () {
    let promise = new Promise((resolve, reject) => {
      let setTimer = setInterval(
        () => {
          var second = this.data.second - 1;
          this.setData({
            second: second,
            btnValue: second+'秒',
            btnDisabled: true
          })
          if (this.data.second <= 0) {
            this.setData({
              second: 60,
              btnValue: '获取验证码',
              btnDisabled: false
            })
            resolve(setTimer)
          }
        }
        , 1000)
    })
    promise.then((setTimer) => {
      clearInterval(setTimer)
    })
}, 

//这部分是往云数据库注册，提交表单信息
cloudRegist: function () {
    var myreg = /^(13[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8}$$/;
    //手机号处理
    if (this.data.phone == "") {
      wx.showToast({
        title: "手机号不能为空",
        icon: "none",
        duration: 1000
      })
      return false;
    } else if (!myreg.test(this.data.phone)) {
      wx.showToast({
        title: "请输入正确的手机号",
        icon: 'none',
        duration: 1000
      })
      return false;
    } else if (this.data.isCode == "") {   //处理验证码
      wx.showToast({
        title: "验证码不能为空",
        icon: 'none',
        duration: 1000
      })
      return false;
    } else if (this.data.isCode != this.data.smscode) {
      wx.showToast({
        title: "验证码错误",
        icon: 'none',
        duration: 1000
      })
      return false;
    } else if (this.data.password == '') {  //密码处理
      wx.showToast({
        title: "密码不能为空",
        icon: 'none',
        duration: 1000
      })
      return false;
    } else if (this.data.repassword == '') {
      wx.showToast({
        title: "请再输入一遍密码不能为空",
        icon: 'none',
        duration: 1000

      })
      return false;
    } else if (this.data.password != this.data.repassword) {
      wx.showToast({
        title: "两次输入的密码不一致！",
        icon: 'none',
        duration: 1000
      })
      return false;
    } else {
      //提交注册信息
      var _this = this;
      const db = wx.cloud.database()
      db.collection('users').add({
        data: {
          phone: this.data.phone,          //手机号
          password: this.data.password,    //密码
          name: this.data.name,            //姓名
          custServer: false,    //是否客服 
          menber: false         //是否会员

        },
        success: res => {
          // 在返回结果中会包含新创建的记录的 _id
          this.setData({
            counterId: res._id,   //这个值没什么用
            
          })
          wx.showModal({
            title: '恭喜您',
            content: '已成功注册，祝学习愉快！',
            showCancel: false, //是否显示取消按钮-----》false去掉取消按钮
            //cancelText: "否",  //默认是“取消”
            //cancelColor: 'skyblue', //取消文字的颜色
            confirmText: "确定",    //默认是“确定”
            confirmColor: 'skyblue', //确定文字的颜色

            success: function (res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '../login/login',
                })
              }
              else { wx.navigateBack({ delta: 2 }) } //else
            }

          }) //success

          console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '新增记录失败'
          })
          console.error('[数据库] [新增记录] 失败：', err)
        }
      })
    }
},


//这部分是往后台数据库注册，提交表单信息
regist:function(){
     var myreg=/^(13[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8}$$/;
     //手机号处理
     if(this.data.phone==""){
       wx.showToast({
         title:"手机号不能为空",
         icon:"none",
         duration:1000
       })
       return false;
     }else if(!myreg.test(this.data.phone)){
      wx.showToast({
        title:"请输入正确的手机号",
        icon:'none',
        duration:1000
       })
       return false;
    } else if(this.data.isCode==""){   //处理验证码
      wx.showToast({
        title:"验证码不能为空",
        icon:'none',
        duration:1000
      })
      return false;
    }else if (this.data.isCode !=this.data.smscode){
      wx.showToast({
        title:"验证码错误",
        icon:'none',
        duration:1000
      })
      return false;
    } else if (this.data.name == '') {  //密码处理
      wx.showToast({
        title: "姓名不能为空",
        icon: 'none',
        duration: 1000

      })
      return false;
    } 
     else {
       var _this = this;

         wx.request({
         url: 'https://www.beicho.com/regist.php',
         method: 'GET',
         header: { 'content-type': 'application/json'},
         data: {
           openid:app.globalData.openid,
           phone: this.data.phone,
           name: this.data.name,
           address:this.data.address,
           school:this.data.school
         },
         success: function (res) {
                
           wx.showModal({
             title: '恭喜您',
             content: '信息完善成功，祝学习愉快！',
             showCancel: false, //是否显示取消按钮-----》false去掉取消按钮
             confirmText: "确定",    //默认是“确定”
             confirmColor: 'skyblue', //确定文字的颜色
                
             success: function (res) {
            
             if (res.confirm) { wx.navigateBack({
                   delta: 2 })
                   } 
              else { wx.navigateBack({ delta: 2 }) } //else
             }

            }) //success
               
          }, //seccess 

         fail: function ({ errMsg }) {
           console.log("request fail", errMsg)
           this.setData({
             loading: false
           })
         } //fail

    }) //wx.request


 }
},


reback:function(){
  wx.navigateBack({
    delta: 1
  })
},
 
/**生命周期函数据，监听页面加载 */
onLoad: function (options) {
 
  wx.cloud.init({
     env: 'test-13579',
     traceUser: true
  });


},

/**生命周期函数据，监听页面初次渲染完成 */
onReady:function(){

},

 /**生命周期函数据，监听页面显示 */
onShow: function () {
//显示个人信息
  var _this = this;
   // console.log(app.globalData.openid)
  wx.request({
    url: 'https://www.beicho.com/regist_qry_personinfo.php',
    method: 'GET',
    header: { 'content-type': 'application/json' },
    data: {
      openid: app.globalData.openid,
    },
    success: function (res) {
     // console.log(res.data.phone)
      _this.setData({
        phone:res.data.phone,
        name:res.data.name,
        address:res.data.address,
        school:res.data.school
     })

    }, //seccess 

    fail: function ({ errMsg }) {
      console.log("request fail", errMsg)
      this.setData({
        loading: false
      })
    } //fail

  }) //wx.request


},


  /**生命周期函数据，监听页面隐藏 */
  onHide: function () {

  },

  /**生命周期函数据，监听页面卸载 */
  onUnload: function () {

  },
  /**页面相关事件处理函数，监听用户下接动作*/
  onPullDownRefresh: function () {

  },

  /**页面上接角底事件的处理函数 */
  onReachBottom: function () {

  },

  /**户用点击灰上角分离 */
  onShareAppMessage: function () {

  }

})